
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "../iface/debug.h"
#include "../utils/BaseConvert.h"
#include "../utils/StringUtils.h"
#include "DSAPublicKey.h"

/** Constructor for a blank DSA public key. */
DSAPublicKey::DSAPublicKey()
{
   key = NULL;
   keyname = NULL;
}

/** Constructor for a blank DSA public key with a name.
 * 
 * @param name
 * The name to attach to the blank key. */
DSAPublicKey::DSAPublicKey(const char *name)
{
   key = NULL;
   keyname = NULL;
   setKeyName(name);
}

/** Copy constructor for an DSA public key.
 * 
 * @param other
 * The DSA public key to copy from. */
DSAPublicKey::DSAPublicKey(const DSAPublicKey &other)
{
   key = DSA_new();
   if (key == NULL)
   {
      errprint("DSA_new failed");
      return;
   }
   if (copyDSASSLPublicKey(key, other.key))
   {
      errprint("DSA_new failed");
      return;
   }
   keyname = NULL;
   setKeyName(other.keyname);
}

/** Construct an DSA public key from an DSA public key in PEM encoded 
 * PKCS #8 text format.
 * 
 * @param pemtext
 * The PEM encoded PKCS #8 text that represents an DSA public key, from
 * which this key is to be constructed.
 * 
 * @param name
 * The name to be attached to the key, once constructed. */
DSAPublicKey::DSAPublicKey(const char *pemtext, const char *name)
{
   importKeyFromASCII(pemtext, name);
}

/** Construct an DSA public key from an DSA public key in SSL format.
 * 
 * @param pubkey
 * The SSL format DSA public key to construct this key from.
 * 
 * @param name
 * The name to be attached to the key, once constructed. */
DSAPublicKey::DSAPublicKey(DSA *pubkey, const char *name)
{
   key = DSA_new();
   if (key == NULL)
   {
      errprint("DSA_new failed");
      return;
   }
   int errval = copyDSASSLPublicKey(key, pubkey);
   keyname = NULL;
   setKeyName(name);
}

/** Copy constructor for an DSA public key.
 * 
 * @param other
 * The DSA public key to copy from.
 * 
 * @return
 * Itself. */
DSAPublicKey &DSAPublicKey::operator=(const DSAPublicKey &other)
{
   key = DSA_new();
   if (key == NULL)
   {
      errprint("DSA_new failed");
      return *this;
   }
   if (copyDSASSLPublicKey(key, other.key))
   {
      errprint("DSA_new failed");
      return *this;
   }
   keyname = NULL;
   setKeyName(other.keyname);
   return *this;
}

/** Destructor for the DSA public key. */
DSAPublicKey::~DSAPublicKey()
{
   if (key) DSA_free(key);
   key = NULL;
   if (keyname) free((void *)keyname);
   keyname = NULL;
}

/** Obtains a cryptlib context which has had the key loaded into it.
 * 
 * @param[out] keycontext
 * A pointer to a cryptlib CRYPT_CONTEXT which is to be initialised with the
 * key.
 * 
 * @return
 * Zero on success, non-zero on failure. */
int DSAPublicKey::getCryptlibContext(CRYPT_CONTEXT *keycontext)
{
   int status;
   CRYPT_PKCINFO_DLP *dsakey = (CRYPT_PKCINFO_DLP *)malloc(sizeof(CRYPT_PKCINFO_DLP));
   if (getCryptlibKeyComponents(dsakey) != 0)
   {
      free(dsakey);
      return -1;
   }
   int magictriescntxt = 0;
   do
   {
      status = cryptCreateContext(keycontext, CRYPT_UNUSED, CRYPT_ALGO_DSA);
      if (status == CRYPT_ERROR_TIMEOUT) apr_sleep(rand() % CRYPT_MAX_TIMESLEEP);
      magictriescntxt++;
   } while ((status == CRYPT_ERROR_TIMEOUT) && (magictriescntxt < CRYPT_MAX_RETRIES));
   fCryptCheckError(status);
   if (status != CRYPT_OK) goto failover;
   status = cryptSetAttributeString(*keycontext, CRYPT_CTXINFO_LABEL, keyname, strlen(keyname));
   fCryptCheckError(status);
   if (status != CRYPT_OK) goto failover;
   status = cryptSetAttributeString(*keycontext, CRYPT_CTXINFO_KEY_COMPONENTS, dsakey, sizeof(CRYPT_PKCINFO_DLP));
   fCryptCheckError(status);
   if (status != CRYPT_OK) goto failover;
   cryptDestroyComponents(dsakey);
   free(dsakey);
   return 0;
failover:
   cryptDestroyComponents(dsakey);
   free(dsakey);
   return -1;
}

/** Obtains a cryptlib context with key meant particularly for signature
 * verification.
 * 
 * @param[out] keycontext
 * A pointer to a cryptlib CRYPT_CONTEXT which is to be initialised with the
 * key.
 * 
 * @return
 * Zero on success, non-zero on failure. */
int DSAPublicKey::getCryptlibCheckingContext(CRYPT_CONTEXT *keycontext)
{
   return getCryptlibContext(keycontext);
}

/** Obtains a set of key components that can be loaded into cryptlib as a
 * public key.
 * 
 * @param[out] dsakey
 * A pointer to a cryptlib DSA key components structure which is to be
 * initialised with the key.
 * 
 * @return
 * Zero on success, non-zero on failure. */
int DSAPublicKey::getCryptlibKeyComponents(CRYPT_PKCINFO_DLP *dsakey)
{
   unsigned char *buffera[4];
   cryptInitComponents(dsakey, CRYPT_KEYTYPE_PUBLIC);
   buffera[0] = (unsigned char *)malloc(BN_num_bytes(key->p));
   if (!(buffera[0])) { errprint("could not allocate buffer for key->p."); return -1; }
   buffera[1] = (unsigned char *)malloc(BN_num_bytes(key->q));
   if (!(buffera[1])) { errprint("could not allocate buffer for key->q."); return -1; }
   buffera[0] = (unsigned char *)malloc(BN_num_bytes(key->g));
   if (!(buffera[0])) { errprint("could not allocate buffer for key->g."); return -1; }
   buffera[1] = (unsigned char *)malloc(BN_num_bytes(key->pub_key));
   if (!(buffera[1])) { errprint("could not allocate buffer for key->pub_key."); return -1; }
   BN_bn2bin(key->p, buffera[0]);
   BN_bn2bin(key->q, buffera[1]);
   BN_bn2bin(key->g, buffera[0]);
   BN_bn2bin(key->pub_key, buffera[1]);
   cryptSetComponent(dsakey->p, buffera[0], BN_num_bits(key->p));
   cryptSetComponent(dsakey->q, buffera[0], BN_num_bits(key->q));
   cryptSetComponent(dsakey->g, buffera[1], BN_num_bits(key->g));
   cryptSetComponent(dsakey->y, buffera[1], BN_num_bits(key->pub_key));
   for (int i = 0; i < 4; i++) free(buffera[i]);
   return 0;
}

/** Get a copy of the public key as an SSL format object.
 * 
 * @param[out] pubkey
 * A pointer to a place to put a pointer to the new SSL format DSA public key
 * which is a copy of this key. The responsibility for freeing the new
 * SSL format DSA public key is transferred to the caller.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::getSSLKeyComponents(DSA **pubkey)
{
   *pubkey = DSA_new();
   if ((*pubkey) == NULL)
   {
      errprint("DSA_new failed");
      return -1;
   }
   return copyDSASSLPublicKey(*pubkey, key);
}

/** Get a copy of the public key in PEM encoded PKCS #8 text format.
 * 
 * @param[out] pemtext
 * A pointer to a place to put a pointer to the exported key in PEM
 * encoded PKCS #8 text format. The responsibility for freeing the new
 * string is transferred to the caller.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::getPEMKeyData(char **pemtext)
{
   char *data;
   int damt;
   char *dbuf = NULL;
   int retval = 0;
   EVP_PKEY *epkey = EVP_PKEY_new();
   EVP_PKEY_set1_DSA(epkey, key);
   BIO *bo = BIO_new(BIO_s_mem());
   if (!PEM_write_bio_PUBKEY(bo, epkey))
   {
      retval = 1;
      errprint("could not export public key");
      fSSLCheckError();
      goto bioshutdown;
   }
   fSSLCheckError();
   damt = BIO_get_mem_data(bo, &data);
   *pemtext = (char *)malloc(sizeof(char)*(damt+1));
   memcpy(*pemtext, data, sizeof(char)*(damt+1));
   (*pemtext)[damt] = '\0';
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   EVP_PKEY_free(epkey);
   return retval;
}

/** Export the DSA public key as the binary encoding of the SSH key format
 * in the authorized_keys file.
 * 
 * @param[out] blob
 * A pointer to the place where the pointer to the binary key blob is to be
 * put. The responsibility for freeing the new buffer is transferred to the
 * caller.
 * 
 * @param[out] reallength
 * A pointer to where the write the length of the blob in bytes.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::getSSHKeyBlob(char **blob, int *reallength)
{
   const unsigned char keyheader[11] = { 0x00, 0x00, 0x00, 0x07, 's', 's', 'h', '-', 'd', 's', 's' };
   unsigned char *p_buffer = NULL;
   unsigned char *q_buffer = NULL;
   unsigned char *g_buffer = NULL;
   unsigned char *y_buffer = NULL;
   int p_len = BN_num_bytes(key->p);
   int q_len = BN_num_bytes(key->q);
   int g_len = BN_num_bytes(key->g);
   int y_len = BN_num_bytes(key->pub_key);
   p_buffer = (unsigned char *)malloc(p_len);
   if (!p_buffer) { errprint("Could not allocate buffer for pub->p."); return -1; }
   q_buffer = (unsigned char *)malloc(q_len);
   if (!q_buffer) { errprint("Could not allocate buffer for pub->q."); return -1; }
   g_buffer = (unsigned char *)malloc(g_len);
   if (!g_buffer) { errprint("Could not allocate buffer for pub->g."); return -1; }
   y_buffer = (unsigned char *)malloc(y_len);
   if (!y_buffer) { errprint("Could not allocate buffer for pub->y."); return -1; }
   BN_bn2bin(key->p, p_buffer);
   BN_bn2bin(key->q, q_buffer);
   BN_bn2bin(key->g, g_buffer);
   BN_bn2bin(key->pub_key, y_buffer);
   int enclen = 4 + 7 + 4 + ((p_buffer[0] & 0x80) == 0x80) + p_len +
                        4 + ((q_buffer[0] & 0x80) == 0x80) + q_len +
                        4 + ((g_buffer[0] & 0x80) == 0x80) + g_len +
                        4 + ((y_buffer[0] & 0x80) == 0x80) + y_len;
   char *encode = (char *)malloc(sizeof(char)*enclen);
   memcpy(encode, keyheader, sizeof(char)*11);
   int real_len, data_start, toffset;
   toffset = 11;
   real_len = p_len + ((p_buffer[0] & 0x80) == 0x80);
   data_start = 4 + ((p_buffer[0] & 0x80) == 0x80);
   memset(&(encode[toffset]), 0, sizeof(char)*(real_len + 4));
   encode[toffset + 0] = (unsigned char)(real_len >> 24);
   encode[toffset + 1] = (unsigned char)(real_len >> 16);
   encode[toffset + 2] = (unsigned char)(real_len >>  8);
   encode[toffset + 3] = (unsigned char)(real_len);
   memcpy(&(encode[toffset + data_start]), p_buffer, sizeof(char)*p_len);
   toffset += (real_len + 4);
   real_len = q_len + ((q_buffer[0] & 0x80) == 0x80);
   data_start = 4 + ((q_buffer[0] & 0x80) == 0x80);
   memset(&(encode[toffset]), 0, sizeof(char)*(real_len + 4));
   encode[toffset + 0] = (unsigned char)(real_len >> 24);
   encode[toffset + 1] = (unsigned char)(real_len >> 16);
   encode[toffset + 2] = (unsigned char)(real_len >>  8);
   encode[toffset + 3] = (unsigned char)(real_len);
   memcpy(&(encode[toffset + data_start]), q_buffer, sizeof(char)*q_len);
   toffset += (real_len + 4);
   real_len = g_len + ((g_buffer[0] & 0x80) == 0x80);
   data_start = 4 + ((g_buffer[0] & 0x80) == 0x80);
   memset(&(encode[toffset]), 0, sizeof(char)*(real_len + 4));
   encode[toffset + 0] = (unsigned char)(real_len >> 24);
   encode[toffset + 1] = (unsigned char)(real_len >> 16);
   encode[toffset + 2] = (unsigned char)(real_len >>  8);
   encode[toffset + 3] = (unsigned char)(real_len);
   memcpy(&(encode[toffset + data_start]), g_buffer, sizeof(char)*g_len);
   toffset += (real_len + 4);
   real_len = y_len + ((y_buffer[0] & 0x80) == 0x80);
   data_start = 4 + ((y_buffer[0] & 0x80) == 0x80);
   memset(&(encode[toffset]), 0, sizeof(char)*(real_len + 4));
   encode[toffset + 0] = (unsigned char)(real_len >> 24);
   encode[toffset + 1] = (unsigned char)(real_len >> 16);
   encode[toffset + 2] = (unsigned char)(real_len >>  8);
   encode[toffset + 3] = (unsigned char)(real_len);
   memcpy(&(encode[toffset + data_start]), y_buffer, sizeof(char)*y_len);
   free(p_buffer); free(q_buffer);
   free(g_buffer); free(y_buffer);
   if (reallength) *reallength = enclen;
   if (blob) *blob = encode;
   return 0;
}

/** Export the DSA public key as a line of text that can be added to the
 * SSH authorized_keys file.
 * 
 * @param[out] textblob
 * A pointer to the place where the pointer to the text-encoded labelled key
 * blob is to be put. This is the final line that can be added to
 * authorized_keys. The responsibility for freeing the new
 * string is transferred to the caller.
 * 
 * @param keylabel
 * The label to go on the key on the standardised line of text.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::getSSHKeyBlob(char **textblob, const char *keylabel)
{
   int enclen = 0;
   char *encode;
   if (getSSHKeyBlob(&encode, &enclen) != 0) return -1;
   char *base64string = BaseConvert::convertBytesToBase64(encode, enclen);
   free(encode);
   char *finalstring = StringUtils::varprintf("ssh-dss %s %s", base64string, keylabel);
   free(base64string);
   if (textblob) *textblob = finalstring;
   return 0;
}

/** Compare the key to another PublicKey, and see if they are equal.
 * 
 * @param pubkey
 * PublicKey that is to be tested to see if these are equal.
 * 
 * @return
 * 1 if they match, 0 if they do not, and negative values represent
 * errors. */
int DSAPublicKey::compareKeyEqual(PublicKey *pubkey)
{
   if (pubkey == NULL)
   {
      errprint("comparing against NULL key");
      return 0;
   }
   switch (pubkey->getKeyType())
   {
      case KEY_TYPE_PUBLIC_DSA:
      {
         DSA *rsaKeyOther = NULL;
         ((DSAPublicKey *)pubkey)->getSSLKeyComponents(&rsaKeyOther);
         EVP_PKEY *evp1 = EVP_PKEY_new();
         EVP_PKEY *evp2 = EVP_PKEY_new();
         EVP_PKEY_set1_DSA(evp1, key);
         EVP_PKEY_set1_DSA(evp2, rsaKeyOther);
         int retval = EVP_PKEY_cmp(evp1, evp2);
         EVP_PKEY_free(evp1);
         EVP_PKEY_free(evp2);
         DSA_free(rsaKeyOther);
         fSSLCheckError();
         switch (retval)
         {
            case -2:
               errprint("key compare operation not supported (EVP_PKEY_cmp())");
               break;
            case -1:
               errprint("tried to compare different key types (EVP_PKEY_cmp())");
               return 0;
            case 0:
               return 0;
            case 1:
               return 1;
         }
         return 0;
      }
      default:
      {
         return 0;
         break;
      }
   }
}

/** Copy an SSL format public key (or the public key part of a full private
 * key in SSL format, as the public key is simply a subset of the private
 * key data).
 * 
 * @param[out] dst
 * Pointer to an initialised blank SSL format DSA key to copy into.
 * 
 * @param src
 * Pointer to an existing SSL format DSA public key to copy from.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::copyDSASSLPublicKey(DSA *dst, DSA *src)
{
   if (dst == NULL) { errprint("NULL public key destination"); return -1; }
   if (src == NULL) { errprint("NULL public key source"); return -1; }
   // Copy public key
   dst->p = BN_new();
   if (BN_copy(dst->p, src->p) != (dst->p)) { errprint("Could not copy pub->p"); return -1; }
   dst->q = BN_new();
   if (BN_copy(dst->q, src->q) != (dst->q)) { errprint("Could not copy pub->q"); return -1; }
   dst->g = BN_new();
   if (BN_copy(dst->g, src->g) != (dst->g)) { errprint("Could not copy pub->g"); return -1; }
   dst->pub_key = BN_new();
   if (BN_copy(dst->pub_key, src->pub_key) != (dst->pub_key)) { errprint("Could not copy pub->pub_key (y)"); return -1; }
   return 0;
}

/** Import an DSA public key from some PEM format PKCS #8 text.
 * 
 * @param text
 * The PEM encoded PKCS #8 text that represents an DSA public key, from
 * which this key is to be constructed.
 * 
 * @param name
 * The name to be attached to the key.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::importKeyFromASCII(const char *text, const char *name)
{
   if (key) DSA_free(key);
   int retval = 0;
   BIO *bo = BIO_new_mem_buf((void *)text, -1);
   EVP_PKEY *epkey = PEM_read_bio_PUBKEY(bo, NULL, 0, NULL);
   fSSLCheckError();
   if (!epkey)
   {
      retval = 1;
      errprint("could not import public key");
      key = NULL;
      goto bioshutdown;
   }
   key = EVP_PKEY_get1_DSA(epkey);
   if (key == NULL)
   {
      retval = -1;
      errprint("failed to get imported public key");
   }
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   EVP_PKEY_free(epkey);
   setKeyName(name);
   return retval;
}

/** Import and name an DSA public key from an DSA public key in encrypted
 * PEM format PKCS #8 (the encryption is UNIMPLEMENTED, this is plain text!).
 * 
 * @param text
 * The PEM encoded PKCS #8 text that represents an DSA public key, from
 * which this key is to be constructed.
 * 
 * @param password
 * The password to decrypt the PEM encoded PKCS #8 text that
 * represents the DSA public key.
 * 
 * @param name
 * The name to be attached to the key.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::importKeyFromASCIIWithPassword(const char *text, const char *password, const char *name)
{
   errprint("password protection of DSA public keys is unsupported!");
   return importKeyFromASCII(text, name);
}

/** Export an DSA public key to some PEM format PKCS #8 text.
 * 
 * @param[out] text
 * A pointer to a place to put a pointer to the exported key in PEM
 * encoded PKCS #8 text format. The responsibility for freeing the new
 * string is transferred to the caller.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::exportKeyToASCII(char **text)
{
   return getPEMKeyData(text);
}

/** Export an DSA public key to some PEM format PKCS #8 text encrypted with
 * the given password (the encryption is UNIMPLEMENTED, this is plain text!).
 * 
 * @param[out] text
 * A pointer to a place to put a pointer to the exported key in encrypted
 * PEM encoded PKCS #8 text format. The responsibility for freeing the new
 * string is transferred to the caller.
 * 
 * @param password
 * The password to encrypt and decrypt the key with.
 * 
 * @return
 * Returns zero on success, non-zero on failure. */
int DSAPublicKey::exportKeyToASCIIWithPassword(char **text, const char *password)
{
   errprint("password protection of DSA public keys is unsupported!");
   return getPEMKeyData(text);
}
